<script setup lang="ts">
import { service } from '@/apis/index'
import router from '@/router/index'
import { useStore } from '@/store/index'
import { Snackbar } from '@varlet/ui'
import { reactive, ref } from 'vue'
import PicCaptcha from './pic-captcha.vue'
// 
const organizer = inject<string>('organizer', "海淀区")

const { pushStack } = useAppRouter()
const { user } = useStore()

const isViewPassword = ref(false)

const pic = ref()
const form = reactive({
  mobile: '',
  password: '',
  captchaId: '',
  verifyCode: ''
})

const forgotPasswordDialogVisible = ref(false)
const forgotPasswordFormData = reactive({
  mobile: '',
  email: '',
  emailCode: '',
  password: ''
})

// 状态
const saving = ref(false)

async function submit() {
  if (!form.mobile || !form.password || !form.verifyCode) {
    Snackbar.error('请填写所有必填项')
    return
  }

  saving.value = true

  try {
    const response = await service({ path: '/student/index/login', method: 'post', data: form })
    user.setToken(response)
    user.getInfo()
    Snackbar.success('登陆成功')
    // router.push('/')
    router.push('/layout/home')
  } catch (err) {
    pic.value.refresh()
    Snackbar.error(err.message)
  } finally {
    saving.value = false
  }
}

function openForgotPasswordDialog() {
  forgotPasswordDialogVisible.value = true
}

function submitForgotPassword() {
  // 添加忘记密码提交逻辑
  service({ path: '/student/index/retrievepassword', method: 'post', data: forgotPasswordFormData })
    .then(() => {
      Snackbar.success('密码重置成功，请使用新密码登录')
      forgotPasswordDialogVisible.value = false
    })
    .catch((err) => {
      Snackbar.error(err.message)
    })
}

// 发送邮箱验证码
const isSendingCode = ref(false)
const countdown = ref(60)
const isEmailValid = ref(false)
let timer: ReturnType<typeof setInterval>

let debounceTimer: ReturnType<typeof setTimeout>
function sendEmailCode() {
  if (isSendingCode.value || !isEmailValid.value) return
  isSendingCode.value = true

  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => {
    service({
      path: '/student/index/sendEmailCode',
      method: 'post',
      data: { email: forgotPasswordFormData.email }
    })
      .then((r) => {
        forgotPasswordFormData.emailId = r.emailId
        Snackbar.success('验证码发送成功，请前往邮箱查看')
        startCountdown()
      })
      .catch((err) => {
        isSendingCode.value = false
        Snackbar.error(err.message)
      })
  }, 300) // 延迟 300 毫秒
}

function startCountdown() {
  countdown.value = 60
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
      isSendingCode.value = false
    }
  }, 1000)
}

// 邮箱验证
watch(
  () => forgotPasswordFormData.email,
  (newVal) => {
    isEmailValid.value = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(newVal)
  }
)
</script>

<template>
  <router-stack>
    <div class="sign-in">
      <app-header title="登录">
        <template #left>
          <!-- <app-back /> -->
        </template>
      </app-header>

      <div class="logo">
        <var-image src="@/assets/images/logo.png" />
        <div class="name">
          <span>{{ organizer }}信息学竞赛</span>
        </div>
      </div>
      <var-form class="sign-in-form">
        <var-space direction="column" :size="['8vmin', 0]">
          <var-input clearable variant="outlined" placeholder="请输入手机号" v-model="form.mobile" autocomplete="tel">
            <template #prepend-icon>
              <var-icon class="sign-in-form-input-icon" name="phone" />
            </template>
          </var-input>
          <!-- current-password -->
          <var-input clearabl variant="outlined" placeholder="请输入密码" :type="isViewPassword ? 'text' : 'password'"
            v-model="form.password" autocomplete="current-password">
            <template #append-icon>
              <var-icon class="sign-in-form-input-icon" :name="isViewPassword ? 'view' : 'view-outline'"
                @click="isViewPassword = !isViewPassword" />
            </template>
          </var-input>
          <var-input clearabl variant="outlined" type="number" placeholder="请输入图片验证码" v-model="form.verifyCode"
            autocomplete="off">
            <template #prepend-icon>
              <var-icon class="sign-in-form-input-icon" name="security" />
            </template>
            <template #append-icon>
              <pic-captcha ref="pic" v-model.trim="form.captchaId" @change="() => {
                form.verifyCode = ''
              }
                " style="width: 100px; height: 40px" />
            </template>
          </var-input>
          <var-button type="primary" block size="large" auto-loading @click="submit">登录</var-button>
          <var-space class="sign-in-form-text" justify="space-between" align="center">
            <var-space @click="openForgotPasswordDialog">忘记密码</var-space>
            <var-space class="sign-in-form-text" justify="center" @click="router.push('/stacks/sign-up')"> 注册
            </var-space>
          </var-space>
        </var-space>
      </var-form>
    </div>
    <!-- 忘记密码 -->
    <var-popup v-model:show="forgotPasswordDialogVisible" title="忘记密码" width="80%">
      <var-form class="forgot-password-form">
        <var-input clearable class="forgot-password-form-item" variant="outlined" placeholder="请输入手机号"
          v-model="forgotPasswordFormData.mobile" autocomplete="tel">
          <template #prepend-icon>
            <var-icon class="sign-in-form-input-icon" name="phone" />
          </template>
        </var-input>
        <var-input clearable class="forgot-password-form-item" variant="outlined" placeholder="请输入邮箱"
          v-model="forgotPasswordFormData.email" autocomplete="email">
          <template #prepend-icon>
            <var-icon class="sign-in-form-input-icon" name="email" />
          </template>
        </var-input>
        <var-input class="forgot-password-form-item" variant="outlined" placeholder="请输入邮箱验证码"
          v-model="forgotPasswordFormData.emailCode" autocomplete="off">
          <template #append-icon>
            <var-button type="primary" @click="sendEmailCode" :disabled="!isEmailValid || isSendingCode">
              {{ isSendingCode ? `${countdown}s 后重试` : '发送验证码' }}
            </var-button>
          </template>
        </var-input>
        <var-input clearable class="forgot-password-form-item" variant="outlined" placeholder="请输入新密码"
          v-model="forgotPasswordFormData.password" autocomplete="new-password" />
        <var-button type="primary" block size="large" @click="submitForgotPassword">提交</var-button>
      </var-form>
    </var-popup>
  </router-stack>
</template>

<style lang="less" scoped>
.sign-in {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: calc(80px + var(--app-bar-height)) 0 60px;

  &-form {
    // width: 300px;
    width: 90%;
    margin-top: 40px;

    &-input-icon {
      margin-right: 10px;
      font-size: 24px;
    }

    &-text {
      font-size: 14px;
      color: var(--color-primary);
    }
  }
}

.logo {
  height: 50px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;

  img {
    height: 46px;
    border-radius: 50px;
    border: 3px solid #000;
    margin-right: 10px;
  }

  span {
    display: inline-block;
    font-size: var(--app-bar-title-font-size);
    font-weight: bold;
    line-height: 1;
    letter-spacing: 3px;
  }
}

.forgot-password-form {
  max-width: 600px;
  margin: auto;
  padding: 25px;

  .forgot-password-form-item {
    margin: 10px 0;
  }
}
</style>
